//package wechat.Demo;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import wechat.MapUtil;
//import wechat.WxJSUtil;
//import wechat.WxPayUtil;
//import wechat.constants.Ticket;
//import wechat.constants.WechantConstant;
//import wechat.entities.*;
//import wechat.enums.ReturnCodeEnum;
//import wechat.enums.WechatPayTradeTypeEnum;
//import wechat.httpRequest.WechatCgiHttpRequest;
//import wechat.httpRequest.WechatOath2HttpRequest;
//import wechat.httpRequest.WechatPayHttpRequest;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.io.PrintWriter;
//import java.io.UnsupportedEncodingException;
//import java.net.URLEncoder;
//import java.util.*;
//
///****
// * 一下接口根据实际需求修改
// * 如一下接口返回类型均为 Map 请自行修改  可自行修改为实体类
// */
//public class WechatServiceDemo {
//
//    private static Logger log = LoggerFactory.getLogger(WechatServiceDemo.class);
//    /***
//     * 微信公众号支付 接口
//     * @param orderCode  实际需求 订单号
//     * @param money 支付钱数 单位人民币(分)
//     * @param clientIp 请求用户 ip
//     * @param openId 微信openId ip
//     * @param body 商品描述  如  腾讯游戏-充值
//     * @throws Exception
//     */
//    public Map<String, Object> unifiedorderJSAPI(String orderCode,
//                                                 int money,
//                                                 String clientIp,
//                                                 String body,
//                                                 String openId) throws Exception {
//        Map<String, Object> result = new HashMap<>(3);
//        result.put("errno", "300");
//        UnfiedOrderParam unfiedOrderParam = new UnfiedOrderParam();
//        unfiedOrderParam.setAppid(WechantConstant.appId);
//        unfiedOrderParam.setMch_id(WechantConstant.mchId);
//        unfiedOrderParam.setBody(body);
//        unfiedOrderParam.setTotal_fee(money);
//        unfiedOrderParam.setFee_type("CNY");
//        unfiedOrderParam.setSpbill_create_ip(clientIp);
//        unfiedOrderParam.setNotify_url(WechantConstant.notifyUrl);
//        unfiedOrderParam.setOpenid(openId);
//        unfiedOrderParam.setTrade_type(WechatPayTradeTypeEnum.公众号支付.getCode());
//        unfiedOrderParam.setOut_trade_no(orderCode);
//        UnfiedOrderResult UnfiedOrderResult = WechatPayHttpRequest.unifiedorder(unfiedOrderParam, WechantConstant.apiKey);
//        Long timestamp = System.currentTimeMillis() / 1000;
//        //返回状态码  处理
//        if (ReturnCodeEnum.失败.getCode().equals(UnfiedOrderResult.getReturn_code())) {
//            result.put("msg", UnfiedOrderResult.getReturn_msg());
//            return result;
//        }
//        if (ReturnCodeEnum.成功.getCode().equals(UnfiedOrderResult.getReturn_code()) && ReturnCodeEnum.失败.getCode().equals(UnfiedOrderResult.getResult_code())) {
//            result.put("msg", UnfiedOrderResult.getErr_code_des());
//            result.put("errno", UnfiedOrderResult.getErr_code());
//            return result;
//        }
//        if (ReturnCodeEnum.成功.getCode().equals(UnfiedOrderResult.getReturn_code()) && ReturnCodeEnum.成功.getCode().equals(UnfiedOrderResult.getResult_code())) {
//            result.put("msg", "200");
//            result.put("errno", "200");
//            Map<String, Object> data = new HashMap<>();
//            data.put("timeStamp", timestamp+"");
//            data.put("nonceStr", timestamp+"");
//            data.put("package", "prepay_id="+UnfiedOrderResult.getPrepay_id());
//            data.put("signType", "MD5");
//            data.put("appId", UnfiedOrderResult.getAppid());
//
//
//
//            SortedMap<Object, Object> params = new TreeMap<Object, Object>();
//            params.put("appId", UnfiedOrderResult.getAppid());
//            params.put("signType","MD5");
//            params.put("package", "prepay_id="+UnfiedOrderResult.getPrepay_id());
//            params.put("nonceStr", timestamp+"");
//            params.put("timeStamp",timestamp+"");
//            log.info("生成sign 参数"+params.toString());
//            String sign = WxPayUtil.createSign("UTF-8", params,  WechantConstant.apiKey);
//            log.info("返回的appid:"+UnfiedOrderResult.getAppid());
//            log.info("返回的package:"+"prepay_id="+UnfiedOrderResult.getPrepay_id());
//            log.info("返回的timeStamp:"+"timeStamp="+timestamp);
//            log.info("生成sign:"+sign);
//
//            data.put("paySign",sign);
//
//            result.put("data", data);
//            return result;
//        }
//        return result;
//    }
//
//
//    /***
//     * 根据授权返回的code 获取用户详细信息
//     *     之前 授权 scope =snsapi_userinfo(必须)
//     * @param code
//     * @return
//     * @throws UnsupportedEncodingException
//     */
//    public UserInfoResult getWechatUserInfo(String code) throws UnsupportedEncodingException {
//        //todo 获取 access_token
//        Oauth2AccessTokenResult accessToken = getAccessToken(code);
//        if (getAccessToken(code) == null) {
//            //注意处理重新授权
//            return null;
//        }
//        String access_token = accessToken.getAccess_token();
//        String openid = accessToken.getOpenid();
//        String refresh_token = accessToken.getRefresh_token();
//        //todo 查验 access_token 是否有效
//        //todo  无效 刷新 access_token token
//        if (!WechatOath2HttpRequest.checkAccessToken(access_token, openid)) {
//            accessToken = WechatOath2HttpRequest.toRefreshToken( WechantConstant.apiKey, "refresh_token", refresh_token);
//            access_token = accessToken.getAccess_token();
//            openid = accessToken.getOpenid();
//            refresh_token = accessToken.getRefresh_token();
//        }
//        //TODO 获取用户信息
//        UserInfoResult UserInfo = WechatOath2HttpRequest.userInfo(access_token, openid, "zh_CN");
//        return UserInfo;
//    }
//
//    /***
//     * auth  获取access_token
//     * @param code
//     * @return
//     */
//
//    private Oauth2AccessTokenResult getAccessToken(String code) {
//        //todo 获取 access_token
//        Oauth2AccessTokenResult accessToken = WechatOath2HttpRequest.oauth2AccessToken( WechantConstant.apiKey,  WechantConstant.secret, code, "authorization_code");
//        if (200 != (accessToken.getCode())) {
//            //注意重新授权
//            return null;
//        } else {
//            return accessToken;
//        }
//    }
//
//    /***
//     * 获取 js引用配置
//     * @param url
//     * @return
//     */
//
//    public Map<String, Object> getJsConfig(String url) {
//        Map<String, Object> result = new HashMap<>(3);
//        result.put("errno", "300");
//        //检查 ticket是否过期
//        Map<String, Object> check = getTicket(WechantConstant.apiKey, WechantConstant.secret);
//        if (!"200".equals(check.get("errno"))) {
//            result.put("msg", check.get("msg"));
//            return result;
//        }
//        //获取 配置信息
//        Map<String, String> config = WxJSUtil.sign(url, WechantConstant.ticket.value);
//        config.put("appId", WechantConstant.apiKey);
//        result = MapUtil.getRetMap();
//        result.put("data", config);
//        return result;
//    }
//
//
//    /***
//     * 检查更新 ticket
//     * @param appId
//     * @param secretkey
//     * @return
//     */
//    private Map<String, Object> getTicket(String appId, String secretkey) {
//        Map<String, Object> result = new HashMap<>(3);
//        result.put("errno", "300");
//        if (WechantConstant.ticket == null || System.currentTimeMillis() > WechantConstant.ticket.getOverdue()) {
//            synchronized (WechatServiceDemo.class) {
//                if (WechantConstant.ticket == null || System.currentTimeMillis() > WechantConstant.ticket.getOverdue()) {
//                    //获取 access_token
//                    CgiAccessTokenResult token = WechatCgiHttpRequest.getToken("client_credential", appId, secretkey);
//                    if (200 != token.getCode()) {
//                        result.put("msg", token.getErrmsg());
//                        return result;
//                    }
//                    Ticket accessToken = new Ticket();
//                    accessToken.setValue(token.getAccess_token());
//                    accessToken.setOverdue(token.getExpires_in() * 1000 + System.currentTimeMillis());
//                    accessToken.setExpire(token.getExpires_in());
//                    WechantConstant.accessToken = accessToken;
//                    // 获取 ticket
//                    CgiTicketResult ticket = WechatCgiHttpRequest.getTicket(token.getAccess_token());
//                    if (200 != ticket.getCode()) {
//                        result.put("msg", ticket.getErrmsg());
//                        return result;
//                    }
//                    Ticket ticket1 = new Ticket();
//                    ticket1.setValue(ticket.getTicket());
//                    ticket1.setOverdue(ticket.getExpires_in() * 1000 + System.currentTimeMillis());
//                    ticket1.setExpire(ticket.getExpires_in());
//                    WechantConstant.ticket = ticket1;
//                }
//            }
//
//        }
//        result = MapUtil.getRetMap();
//        return result;
//
//    }
//
//    /***
//     * 微信 token验证服务器
//     * @param request
//     * @param response
//     * @throws IOException
//     */
//    public void wxToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        // / 微信加密签名
//        String signature = request.getParameter("signature");
//        // / 时间戳
//        String timestamp = request.getParameter("timestamp");
//        // / 随机数
//        String nonce = request.getParameter("nonce");
//        // 随机字符串
//        String echostr = request.getParameter("echostr");
//        PrintWriter printWriter = response.getWriter();
//        if (WxJSUtil.checkSignature(WechantConstant.token, signature, timestamp, nonce)) {
//            printWriter.print(echostr);
//            System.out.println("========微信认证token成功========= ");
//        } else {
//            System.out.println("========微信认证token失败========= ");
//        }
//        printWriter.flush();
//        printWriter.close();
//
//    }
//
//
//    /***
//     * 获取授权登录页
//     *  扫码微信授权
//     *
//     * @param url 根据实际需要可以添加参数 url拼接即可
//     * @param  scope   传参看 AuthScope
//     * @param response
//     * @throws IOException
//     */
//    public void getWechatUser(
//                              String  url,
//                              String  scope,
//                              HttpServletResponse response
//
//    ) throws IOException {
//        String response_type = "code";
//        String state = "state";
//        //拼接 登录 url
//        response.sendRedirect(
//                WechatOath2HttpRequest.toWechantLogin(
//                        WechantConstant.appId,
//                        WechantConstant.hostUrl + url,
//                        response_type,
//                        scope,
//                        state)
//        );
//    }
//
//    /***
//     * 通过code获取用户信息(openId)
//     * @param code  微信返回的code
//     * @return
//     */
//    public void getAccessToken( String code,
//                                String merchantId,
//                                String tableId,
//                               HttpServletRequest request,
//                               HttpServletResponse response) throws IOException {
//        Map<String,Object> result = new LinkedHashMap<>(4);
//        Oauth2AccessTokenResult accessToken = WechatOath2HttpRequest.oauth2AccessToken(WechantConstant.appId, WechantConstant.secret, code, "authorization_code");
//        if (accessToken == null) {
//            result.put("merchantId", merchantId);
//            result.put("tableId", tableId);
//            result.put("errno", "416");
//            result.put("msg", URLEncoder.encode("请重新扫码登录","UTF-8"));
//        }
//        request.getSession().removeAttribute("accessToken");
//        request.getSession().setAttribute("accessToken", accessToken);
//
//        result.put("merchantId", merchantId);
//        result.put("tableId", tableId);
//        result.put("errno","200");
//        result.put("msg",  URLEncoder.encode("授权成功","UTF-8"));
//
//        //跳转前端页面
//        response.sendRedirect(WechatOath2HttpRequest.getUrl(WechantConstant.hostUrl+WechantConstant.redirect,result,"授权登录跳转页面"));
//    }
//
//
//}
